package com.kaidi.dibankecloud.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.kaidi.dibankecloud.R;
import com.kaidi.dibankecloud.databinding.ActivityRegisterBinding;
import com.kaidi.dibankecloud.utils.ConstantValues;
import com.kaidi.dibankecloud.utils.ResourceUtils;
import com.kaidi.dibankecloud.utils.WindowUtils;
import com.kaidi.dibankecloud.widget.MaintenancePopupWindow;
import com.kaidi.dibankecloud.widget.ProtocolPopupWindow;
import com.kaidi.dibankecloud.widget.RegSuccessPopupWindow;
import com.kaidi.dibankecloud.widget.TipsPopupWindow;

import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.regex.Pattern;


public class RegisterActivity extends AppCompatActivity implements PopupWindow.OnDismissListener{
    private static final String REGEX_ACCOUNT = "^[a-zA-Z]\\w{5,10}$";
    private static final String REGEX_PASSWORD = "^[a-zA-Z0-9]\\w{5,8}$";
    private static final String REGEX_EMAIL = "^[A-Za-z\\d]+([-_.][A-Za-z\\d]+)*@([A-Za-z\\d]+[-.])+[A-Za-z\\d]{2,5}$";
    private ActivityRegisterBinding binding;
    private boolean accountRight;
    private boolean passwordRight;
    private boolean emailRight;
    private String emailActivatedCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_register);
        WindowUtils.setColor(this, ContextCompat.getColor(this, R.color.colorHighlightBlue));
        Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/fzltxhjt.ttf");
        binding.setRegTypeFace(tf);
        binding.setCurrentActivity(this);
        binding.setTargetActivityClass(MainActivity.class);
        binding.regAccountEt.setOnFocusChangeListener(new RegFocusChangeListener());
        binding.regPwdEt.setOnFocusChangeListener(new RegFocusChangeListener());
        binding.regEmailEt.setOnFocusChangeListener(new RegFocusChangeListener());
        binding.regAccountEt.addTextChangedListener(new RegTextWatcher(RegTextWatcher.ACCOUNT_WATCHER));
        binding.regPwdEt.addTextChangedListener(new RegTextWatcher(RegTextWatcher.PASSWORD_WATCHER));
        binding.regPwdConfirmEt.addTextChangedListener(new RegTextWatcher(RegTextWatcher.PASSWORD_CONFIRM_WATCHER));
        binding.regEmailEt.addTextChangedListener(new RegTextWatcher(RegTextWatcher.EMAIL_WATCHER));
    }

    public boolean checkAccount(){
        String account = binding.regAccountEt.getText().toString();
        if(TextUtils.isEmpty(account)){
            return false;
        }
        String checkResult;
        if(!Pattern.matches(REGEX_ACCOUNT,account)){
            checkResult = getString(R.string.account_illegal);
        }else if(account.equals("123456")){
            checkResult = getString(R.string.account_has_been_registered);
        }else{
            binding.regAccountArea.setBackgroundResource(R.drawable.et_login_ver_normal);
            return true;
        }
        binding.regErrorTv.setText(checkResult);
        binding.regAccountArea.setBackgroundResource(R.drawable.et_login_ver_error);
        return false;
    }

    public boolean checkPassword(){
        String pwd = binding.regPwdEt.getText().toString();
        String pwdConfirm = binding.regPwdConfirmEt.getText().toString();
        if(TextUtils.isEmpty(pwd) && TextUtils.isEmpty(pwdConfirm)){
            return false;
        }
        String checkResult;
        if(!Pattern.matches(REGEX_PASSWORD,pwd)){
            checkResult = getString(R.string.pwd_illegal);
        }else if(!pwd.equals(pwdConfirm)){
            checkResult = getString(R.string.pwd_not_same);
        }else{
            binding.regPwdPfl.setBackgroundResource(R.drawable.bg_login_gray);
            return true;
        }
        binding.regErrorTv.setText(checkResult);
        binding.regPwdPfl.setBackgroundResource(R.drawable.bg_login_red);
        return false;
    }

    public boolean checkEmail(){
        String email = binding.regEmailEt.getText().toString();
        if(TextUtils.isEmpty(email)){
            return false;
        }
        String checkResult;
        if(!Pattern.matches(REGEX_EMAIL,email)){
            checkResult = getString(R.string.email_illegal);
        }else if(!checkIsEnterpriseMail(email)){
            checkResult = getString(R.string.not_enterprise_email);
        }else{
            binding.regEmailArea.setBackgroundResource(R.drawable.et_login_ver_normal);
            return true;
        }
        binding.regErrorTv.setText(checkResult);
        binding.regEmailArea.setBackgroundResource(R.drawable.et_login_ver_error);
        return false;
    }

    public boolean checkIsEnterpriseMail(String email){
        String companyName;
        try {
            companyName = email.substring(email.indexOf("@")+1, email.indexOf("."));
        }catch(IndexOutOfBoundsException e){
            companyName = email.substring(email.indexOf("@")+1, email.indexOf("-"));
        }
        for (int i = 0; i < ConstantValues.PUBLIC_EMAIL_COMPANY.length; i++) {
            if(companyName.equals(ConstantValues.PUBLIC_EMAIL_COMPANY[i])){
                return false;
            }
        }
        return true;
    }

    public void regActivityClick(View view){
        switch (view.getId()) {
            case R.id.reg_account_clear_btn:
                binding.regAccountEt.setText("");
                break;
            case R.id.reg_login_text_bottom:
                startActivity(new Intent(this,MainActivity.class));
                break;
            case R.id.reg_btn:
                accountRight = checkAccount();
                passwordRight = checkPassword();
                emailRight = checkEmail();
                if(accountRight && passwordRight && emailRight){
                    binding.regErrorTv.setText("");
                    if (!((BaseApplication) getApplication()).isNetConnected()) {
                        final TipsPopupWindow tipsPopupWindow = new TipsPopupWindow(this, getResources().getDrawable(R.drawable.ic_login_error), getString(R.string.network_error), Color.BLACK);
                        tipsPopupWindow.setOutsideTouchable(true);
                        tipsPopupWindow.showPopupWindow(binding.getRoot());
                        tipsPopupWindow.setOnDismissListener(this);
                        new CountDownTimer(3000, 1000){
                            @Override
                            public void onTick(long l) {}
                            @Override
                            public void onFinish() {
                                if(tipsPopupWindow.isShowing()){
                                    tipsPopupWindow.dismiss();
                                }
                            }
                        }.start();
                    }else{
                        Calendar today = Calendar.getInstance();
                        if (today.get(Calendar.DAY_OF_MONTH) == Calendar.SUNDAY) {
                            final MaintenancePopupWindow maintenancePopupWindow = new MaintenancePopupWindow(this);
                            maintenancePopupWindow.showPopupWindow(binding.getRoot());
                            maintenancePopupWindow.setOnDismissListener(this);
                            new CountDownTimer(5000, 1000){
                                @Override
                                public void onTick(long l) {}
                                @Override
                                public void onFinish() {
                                    if(maintenancePopupWindow.isShowing()){
                                        maintenancePopupWindow.dismiss();
                                    }
                                }
                            }.start();
                        }else{
                            emailActivatedCode = ResourceUtils.generateFourNumbers();
                            Log.d("1212",emailActivatedCode);
//                            EditUtils.sendActivatedEmail(binding.regEmailEt.getText().toString(),emailActivatedCode);
                            RegSuccessPopupWindow regSuccessPopupWindow = new RegSuccessPopupWindow(this);
                            regSuccessPopupWindow.showPopupWindow(binding.getRoot());
                            regSuccessPopupWindow.setOnDismissListener(this);
                        }
                    }
                }
                break;
            case R.id.reg_user_agreement:
                showProtocolPopupWindow("user_agreement.txt");
                break;
            case R.id.reg_user_protocol:
                showProtocolPopupWindow("user_protocol.txt");
                break;
        }
    }

    public void showProtocolPopupWindow(String fileName){
        try {
            InputStream is = getAssets().open(fileName);
            String content = ResourceUtils.readTextFromAssets(is);
            ProtocolPopupWindow protocolPopupWindow = new ProtocolPopupWindow(this, content);
            protocolPopupWindow.showPopupWindow(binding.getRoot());
            protocolPopupWindow.setOnDismissListener(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDismiss() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1f;
        getWindow().setAttributes(lp);
    }

    public String getEmailActivatedCode() {
        return emailActivatedCode;
    }

    private class RegFocusChangeListener implements View.OnFocusChangeListener{
        @Override
        public void onFocusChange(View view, boolean hasFocus) {
            if(hasFocus){
                accountRight = checkAccount();
                passwordRight = checkPassword();
                emailRight = checkEmail();
            }
        }
    }

    private class RegTextWatcher implements TextWatcher{
        private static final int ACCOUNT_WATCHER = 1010;
        private static final int PASSWORD_WATCHER = 2020;
        private static final int PASSWORD_CONFIRM_WATCHER = 3030;
        private static final int EMAIL_WATCHER = 4040;
        private int flag;
        private RegTextWatcher(int flag) {
            this.flag = flag;
        }
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
        @Override
        public void afterTextChanged(Editable editable) {
            switch (flag) {
                case ACCOUNT_WATCHER:
                    String content = editable.toString();
                    if(!TextUtils.isEmpty(content)) {
                        binding.regAccountClearBtn.setVisibility(View.VISIBLE);
                    }else{
                        binding.regAccountClearBtn.setVisibility(View.GONE);
                    }
                    if(!accountRight){
                        binding.regAccountArea.setBackgroundResource(R.drawable.et_login_ver_normal);
                    }
                    break;
                case PASSWORD_WATCHER:
                case PASSWORD_CONFIRM_WATCHER:
                    if(!passwordRight){
                        binding.regPwdPfl.setBackgroundResource(R.drawable.bg_login_gray);
                    }
                    break;
                case EMAIL_WATCHER:
                    if(!emailRight){
                        binding.regEmailArea.setBackgroundResource(R.drawable.et_login_ver_normal);
                    }
                    break;
            }
            binding.regErrorTv.setText("");
            String account = binding.regAccountEt.getText().toString();
            String pwd = binding.regPwdEt.getText().toString();
            String confirmPwd = binding.regPwdConfirmEt.getText().toString();
            String email = binding.regEmailEt.getText().toString();
            binding.regBtn.setEnabled(!TextUtils.isEmpty(account) && !TextUtils.isEmpty(pwd) &&
                        !TextUtils.isEmpty(confirmPwd) && !TextUtils.isEmpty(email));
        }
    }
}
